<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>信息技术-选择题模块练习系统</title>
    <link href="./dist/output.css" rel="stylesheet">
    <style>
        .gradient-bg {
            background: linear-gradient(135deg, #e0f2fe 0%, #f0e7ff 50%, #fce7f3 100%);
        }
        .glass-effect {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.1);
        }
    </style>
</head>
<body class="gradient-bg min-h-screen">
    <!-- 顶部标题 -->
    <div class="w-full px-4 py-8 flex justify-between items-center">
        <h1 class="text-3xl font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-blue-600 to-purple-600 tracking-wide">
            信息技术-选择题模块练习系统
        </h1>
        <div class="flex gap-4">
            <button id="exportBtn" class="px-4 py-2 bg-green-100 text-green-700 rounded-lg hover:bg-green-200 text-sm font-medium transition-colors hidden">
                导出结果
            </button>
            <button id="restartBtn" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 text-sm font-medium transition-colors hidden">
                重新答题
            </button>
        </div>
    </div>
    <div class="container mx-auto px-4 pb-8 h-[calc(100vh-8rem)]">
        <div class="flex gap-6 h-full">
            <!-- 左侧信息栏 -->
            <div class="w-72 glass-effect rounded-xl shadow-lg p-4 flex flex-col">
                <div class="w-full mb-4">
                    <div class="mb-2 flex items-center">
                        <span class="text-gray-700 font-medium w-14">班级：</span>
                        <span id="studentClass" class="text-gray-900 font-semibold">--</span>
                    </div>
                    <div class="mb-2 flex items-center">
                        <span class="text-gray-700 font-medium w-14">姓名：</span>
                        <span id="studentName" class="text-gray-900 font-semibold">--</span>
                    </div>
                </div>
                <div class="w-full mt-2 flex-1 flex flex-col">
                    <div class="mb-2 text-gray-600 font-semibold text-sm">答题进度</div>
                    <div id="questionNavWrapper" class="overflow-x-auto pb-2">
                        <div id="questionNav" class="grid grid-cols-6 gap-1.5"></div>
                    </div>
                    <div id="statusInfo" class="mt-3 flex justify-between text-xs">
                        <span class="text-gray-400">未作答</span>
                        <span class="text-blue-500">当前题</span>
                        <span class="text-green-600">已作答</span>
                    </div>
                </div>
            </div>
            <!-- 右侧答题区 -->
            <div class="flex-1 glass-effect rounded-xl shadow-lg p-6 flex flex-col overflow-hidden">
                <div class="flex-1 overflow-y-auto pr-2">
                    <div class="mb-6">
                        <h2 class="text-xl font-semibold mb-3 text-gray-800">题目</h2>
                        <p id="questionText" class="text-gray-700 leading-relaxed" style="white-space: pre-wrap;"></p>
                    </div>
                    <div class="space-y-4">
                        <div class="flex items-center p-3 rounded-lg hover:bg-gray-50 transition-colors">
                            <input type="radio" name="answer" id="optionA" value="A" class="h-4 w-4 text-blue-600">
                            <label for="optionA" class="ml-3 text-gray-700 cursor-pointer">A. <span id="optionAText"></span></label>
                        </div>
                        <div class="flex items-center p-3 rounded-lg hover:bg-gray-50 transition-colors">
                            <input type="radio" name="answer" id="optionB" value="B" class="h-4 w-4 text-blue-600">
                            <label for="optionB" class="ml-3 text-gray-700 cursor-pointer">B. <span id="optionBText"></span></label>
                        </div>
                        <div class="flex items-center p-3 rounded-lg hover:bg-gray-50 transition-colors">
                            <input type="radio" name="answer" id="optionC" value="C" class="h-4 w-4 text-blue-600">
                            <label for="optionC" class="ml-3 text-gray-700 cursor-pointer">C. <span id="optionCText"></span></label>
                        </div>
                        <div class="flex items-center p-3 rounded-lg hover:bg-gray-50 transition-colors">
                            <input type="radio" name="answer" id="optionD" value="D" class="h-4 w-4 text-blue-600">
                            <label for="optionD" class="ml-3 text-gray-700 cursor-pointer">D. <span id="optionDText"></span></label>
                        </div>
                    </div>
                </div>
                <div class="mt-6 pt-4 border-t">
                    <div class="flex justify-between items-center">
                        <div class="flex gap-4">
                            <button id="prevBtn" class="px-4 py-2 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                                上一题
                            </button>
                            <button id="nextBtn" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm font-medium transition-colors">
                                下一题
                            </button>
                        </div>
                        <button id="submitBtn" class="px-8 py-2.5 bg-gradient-to-r from-orange-400 to-orange-500 text-white rounded-lg hover:from-orange-500 hover:to-orange-600 font-bold transition-all shadow-md hover:shadow-lg">
                            交卷
                        </button>
                    </div>
                </div>
                <!-- 答题结果区域 -->
                <div id="resultArea" class="mt-6 hidden">
                    <div class="border-t pt-4">
                        <h3 class="text-lg font-semibold mb-4 text-gray-800">答题结果</h3>
                        <div id="resultContent" class="space-y-4"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 学生信息输入弹窗 -->
    <div id="infoModal" class="fixed inset-0 bg-black bg-opacity-40 flex items-center justify-center z-50">
        <div class="glass-effect rounded-xl p-8 w-full max-w-sm mx-4">
            <h2 class="text-2xl font-bold text-center mb-6 text-gray-800">请输入信息</h2>
            <div class="mb-4">
                <label class="block mb-2 text-gray-700 font-medium">班级</label>
                <select id="classSelect" class="w-full px-4 py-2.5 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all">
                    <option value="">请选择班级</option>
                </select>
            </div>
            <div class="mb-6">
                <label class="block mb-2 text-gray-700 font-medium">姓名</label>
                <input type="text" id="nameInput" class="w-full px-4 py-2.5 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all" placeholder="请输入姓名">
            </div>
            <button id="startBtn" class="w-full px-4 py-3 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-lg hover:from-blue-600 hover:to-blue-700 font-bold transition-all shadow-md hover:shadow-lg">
                开始答题
            </button>
        </div>
    </div>

    <script src="xlsx.full.min.js"></script>
    <script src="quizdata.js"></script>
    <script>
        // 全局变量
        let currentQuestionIndex = 0;
        let answers = [];
        let studentClass = '';
        let studentName = '';
        // 题目数据自动加载
        let questions = [];
        // 存储题目和选项的随机顺序
        let questionOrder = [];
        let optionOrders = [];

        // DOM 元素
        const questionText = document.getElementById('questionText');
        const optionAText = document.getElementById('optionAText');
        const optionBText = document.getElementById('optionBText');
        const optionCText = document.getElementById('optionCText');
        const optionDText = document.getElementById('optionDText');
        const prevBtn = document.getElementById('prevBtn');
        const nextBtn = document.getElementById('nextBtn');
        const submitBtn = document.getElementById('submitBtn');
        const questionNav = document.getElementById('questionNav');
        const questionNavWrapper = document.getElementById('questionNavWrapper');
        const infoModal = document.getElementById('infoModal');
        const classSelect = document.getElementById('classSelect');
        const nameInput = document.getElementById('nameInput');
        const startBtn = document.getElementById('startBtn');
        const studentClassSpan = document.getElementById('studentClass');
        const studentNameSpan = document.getElementById('studentName');

        // 随机打乱数组顺序
        function shuffleArray(array) {
            const newArray = [...array];
            for (let i = newArray.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
            }
            return newArray;
        }

        // 初始化题目顺序
        function initQuestionOrder() {
            // 生成题目顺序
            questionOrder = shuffleArray(Array.from({length: questions.length}, (_, i) => i));
            // 为每道题生成选项顺序
            optionOrders = questions.map(() => shuffleArray(['A', 'B', 'C', 'D']));
        }

        // 获取原始题号
        function getOriginalQuestionIndex(index) {
            return questionOrder[index];
        }

        // 获取原始选项
        function getOriginalOption(questionIndex, option) {
            return optionOrders[questionIndex][option.charCodeAt(0) - 65];
        }

        // 获取当前选项对应的原始选项
        function getCurrentOption(questionIndex, originalOption) {
            return String.fromCharCode(65 + optionOrders[questionIndex].indexOf(originalOption));
        }

        // 保存答题进度到本地存储
        function saveProgress() {
            const progress = {
                studentClass,
                studentName,
                answers,
                currentQuestionIndex,
                questionOrder,
                optionOrders
            };
            localStorage.setItem('quizProgress', JSON.stringify(progress));
        }

        // 从本地存储加载答题进度
        function loadProgress() {
            const savedProgress = localStorage.getItem('quizProgress');
            if (savedProgress) {
                const progress = JSON.parse(savedProgress);
                studentClass = progress.studentClass;
                studentName = progress.studentName;
                answers = progress.answers;
                currentQuestionIndex = progress.currentQuestionIndex;
                questionOrder = progress.questionOrder;
                optionOrders = progress.optionOrders;
                
                // 更新显示
                studentClassSpan.textContent = studentClass;
                studentNameSpan.textContent = studentName;
                
                // 如果已经完成答题，显示结果
                if (answers.every(answer => answer !== null)) {
                    showResults();
                } else {
                    showCurrentQuestion();
                    renderQuestionNav();
                }
                return true;
            }
            return false;
        }

        // 清除答题进度
        function clearProgress() {
            localStorage.removeItem('quizProgress');
        }

        // 初始化班级下拉
        function initClassSelect() {
            for (let i = 2401; i <= 2429; i++) {
                const opt = document.createElement('option');
                opt.value = `${i}班`;
                opt.textContent = `${i}班`;
                classSelect.appendChild(opt);
            }
        }

        // 初始化
        function init() {
            initClassSelect();
            infoModal.style.display = 'flex';
            startBtn.addEventListener('click', handleStart);
            prevBtn.addEventListener('click', showPreviousQuestion);
            nextBtn.addEventListener('click', showNextQuestion);
            submitBtn.addEventListener('click', () => {
                const unansweredCount = answers.filter(answer => answer === null).length;
                if (unansweredCount > 0) {
                    if (confirm(`还有 ${unansweredCount} 道题目未完成，确定要交卷吗？`)) {
                        showResults();
                    }
                } else {
                    showResults();
                }
            });
            document.getElementById('restartBtn').addEventListener('click', restartQuiz);
            document.getElementById('exportBtn').addEventListener('click', exportResults);
        }

        // 处理开始答题
        function handleStart() {
            const cls = classSelect.value;
            const name = nameInput.value.trim();
            if (!cls) {
                alert('请选择班级！');
                return;
            }
            if (!name) {
                alert('请输入姓名！');
                return;
            }
            studentClass = cls;
            studentName = name;
            studentClassSpan.textContent = cls;
            studentNameSpan.textContent = name;
            infoModal.style.display = 'none';
            startQuiz();
        }

        // 开始测验
        function startQuiz() {
            answers = new Array(questions.length).fill(null);
            currentQuestionIndex = 0;
            initQuestionOrder();
            renderQuestionNav();
            showCurrentQuestion();
            saveProgress();
        }

        // 渲染题号导航
        function renderQuestionNav() {
            questionNav.innerHTML = '';
            for (let i = 0; i < questions.length; i++) {
                const btn = document.createElement('button');
                btn.textContent = i + 1;
                let btnClass = 'w-9 h-7 rounded-md border text-xs font-bold mb-1 ';
                
                if (i === currentQuestionIndex) {
                    btnClass += 'bg-blue-500 text-white';
                } else if (answers[i] === null) {
                    btnClass += 'bg-gray-100 text-gray-400';
                } else {
                    btnClass += 'bg-green-200 text-green-700';
                }
                
                btn.className = btnClass;
                btn.onclick = () => {
                    saveCurrentAnswer();
                    currentQuestionIndex = i;
                    showCurrentQuestion();
                    renderQuestionNav();
                };
                questionNav.appendChild(btn);
            }
        }

        // 更新状态信息显示
        function updateStatusInfo() {
            const statusInfo = document.getElementById('statusInfo');
            if (submitBtn.disabled) {
                // 交卷后显示正确和错误数量
                const correctCount = questions.reduce((total, _, index) => {
                    const originalIndex = getOriginalQuestionIndex(index);
                    const selectedOption = answers[index];
                    const originalOption = selectedOption ? getOriginalOption(originalIndex, selectedOption) : null;
                    return total + (originalOption === questions[originalIndex].答案 ? 1 : 0);
                }, 0);
                const wrongCount = questions.length - correctCount;
                
                statusInfo.innerHTML = `
                    <span class="text-gray-400">未作答：${answers.filter(a => a === null).length}</span>
                    <span class="text-green-600">正确：${correctCount}</span>
                    <span class="text-red-600">错误：${wrongCount}</span>
                `;
            } else {
                // 交卷前显示答题状态
                const answeredCount = answers.filter(a => a !== null).length;
                statusInfo.innerHTML = `
                    <span class="text-gray-400">未作答：${answers.length - answeredCount}</span>
                    <span class="text-blue-500">当前题：${currentQuestionIndex + 1}</span>
                    <span class="text-green-600">已作答：${answeredCount}</span>
                `;
            }
        }

        // 显示当前题目
        function showCurrentQuestion() {
            const originalIndex = getOriginalQuestionIndex(currentQuestionIndex);
            const question = questions[originalIndex];
            const optionOrder = optionOrders[originalIndex];
            
            questionText.textContent = `${currentQuestionIndex + 1}. ${question.题干}`;
            optionAText.textContent = question[`选项${optionOrder[0]}`];
            optionBText.textContent = question[`选项${optionOrder[1]}`];
            optionCText.textContent = question[`选项${optionOrder[2]}`];
            optionDText.textContent = question[`选项${optionOrder[3]}`];
            
            // 恢复已选择的答案
            const selectedOption = document.querySelector(`input[name="answer"][value="${answers[currentQuestionIndex]}"]`);
            if (selectedOption) {
                selectedOption.checked = true;
            } else {
                document.querySelectorAll('input[name="answer"]').forEach(input => {
                    input.checked = false;
                });
            }

            // 如果已交卷，禁用所有单选框
            const radioInputs = document.querySelectorAll('input[name="answer"]');
            radioInputs.forEach(input => {
                input.disabled = submitBtn.disabled;
            });
            
            prevBtn.disabled = currentQuestionIndex === 0;
            nextBtn.disabled = currentQuestionIndex === questions.length - 1;
            
            // 如果已经交卷，更新答题结果和导航
            if (submitBtn.disabled) {
                updateResultDisplay();
                renderQuestionNavAfterSubmit();
            } else {
                renderQuestionNav();
            }
            
            // 更新状态信息
            updateStatusInfo();
            
            // 滚动到当前题号
            setTimeout(() => {
                const navBtns = questionNav.querySelectorAll('button');
                if (navBtns[currentQuestionIndex]) {
                    navBtns[currentQuestionIndex].scrollIntoView({block: 'nearest', inline: 'center', behavior: 'smooth'});
                }
            }, 0);
        }

        // 上一题
        function showPreviousQuestion() {
            saveCurrentAnswer();
            if (currentQuestionIndex > 0) {
                currentQuestionIndex--;
                showCurrentQuestion();
            }
        }

        // 下一题
        function showNextQuestion() {
            saveCurrentAnswer();
            if (currentQuestionIndex < questions.length - 1) {
                currentQuestionIndex++;
                showCurrentQuestion();
            }
        }

        // 保存当前答案
        function saveCurrentAnswer() {
            const selectedOption = document.querySelector('input[name="answer"]:checked');
            if (selectedOption) {
                answers[currentQuestionIndex] = selectedOption.value;
                saveProgress();
                updateStatusInfo();
            }
        }

        // 更新答题结果显示
        function updateResultDisplay() {
            const originalIndex = getOriginalQuestionIndex(currentQuestionIndex);
            const question = questions[originalIndex];
            const selectedOption = answers[currentQuestionIndex];
            const originalOption = selectedOption ? getOriginalOption(originalIndex, selectedOption) : null;
            const isCorrect = originalOption === question.答案;
            
            const resultContent = document.getElementById('resultContent');
            resultContent.innerHTML = `
                <div class="p-4 rounded-lg ${isCorrect ? 'bg-green-50' : 'bg-red-50'}">
                    <div class="font-semibold mb-2">第${currentQuestionIndex + 1}题（原题号：${question.题号}）：${isCorrect ? '✓ 正确' : '✗ 错误'}</div>
                    <div class="text-gray-700 mb-1">你的答案：${selectedOption || '未作答'}</div>
                    <div class="text-gray-700 mb-1">正确答案：${getCurrentOption(originalIndex, question.答案)}</div>
                    <div class="text-gray-600 text-sm">解析：${question.解析 || '暂无解析'}</div>
                </div>
            `;
        }

        // 导出答题结果
        function exportResults() {
            const exportData = {
                studentInfo: {
                    class: studentClass,
                    name: studentName,
                    totalScore: questions.reduce((total, _, index) => {
                const originalIndex = getOriginalQuestionIndex(index);
                const selectedOption = answers[index];
                const originalOption = selectedOption ? getOriginalOption(originalIndex, selectedOption) : null;
                        return total + (originalOption === questions[originalIndex].答案 ? 2 : 0);
                    }, 0),
                    correctCount: answers.reduce((total, ans, index) => {
                        if (ans === null) return total;
                        const originalIndex = getOriginalQuestionIndex(index);
                        const originalOption = getOriginalOption(originalIndex, ans);
                return total + (originalOption === questions[originalIndex].答案 ? 1 : 0);
                    }, 0),
                    wrongCount: answers.reduce((total, ans, index) => {
                        if (ans === null) return total;
                        const originalIndex = getOriginalQuestionIndex(index);
                        const originalOption = getOriginalOption(originalIndex, ans);
                        return total + (originalOption !== questions[originalIndex].答案 ? 1 : 0);
                    }, 0),
                    unansweredCount: answers.filter(a => a === null).length,
                    timestamp: new Date().toLocaleString()
                },
                answerDetails: [],
                questionOrder: questionOrder,
                optionOrders: optionOrders,
                userAnswers: answers 
            };

            const sortedAnswersData = questions.map((_, index) => {
                const originalIndex = getOriginalQuestionIndex(index);
                const currentDisplayIndex = index;
                const studentAnswerDisplayed = answers[currentDisplayIndex];
                const questionData = questions[originalIndex];
                const studentOriginalOption = studentAnswerDisplayed 
                    ? getOriginalOption(originalIndex, studentAnswerDisplayed) 
                    : null;
                const isCorrect = studentOriginalOption === questionData.答案;
                
                return {
                    originalQuestionId: questionData.题号 || (originalIndex + 1).toString(),
                    currentDisplayId: currentDisplayIndex + 1,
                    studentAnswerDisplayed: studentAnswerDisplayed || '未作答',
                    studentOriginalOption: studentOriginalOption || '未作答',
                    correctOriginalOption: questionData.答案,
                    isCorrect: isCorrect ? '正确' : '错误',
                    questionText: questionData.题干,
                    options: { 
                        A: questionData.选项A,
                        B: questionData.选项B,
                        C: questionData.选项C,
                        D: questionData.选项D
                    },
                    explanation: questionData.解析 || ''
                };
            }).sort((a, b) => {
                const numA = parseFloat(a.originalQuestionId.replace(/[^\d.-]/g, '')) || 0;
                const numB = parseFloat(b.originalQuestionId.replace(/[^\d.-]/g, '')) || 0;
                return numA - numB;
            });

            exportData.answerDetails = sortedAnswersData;

            let checksumContent = JSON.stringify(exportData.studentInfo) + JSON.stringify(exportData.answerDetails) + "SOME_SECRET_SALT";
            let checksum = 0;
            for (let i = 0; i < checksumContent.length; i++) {
                checksum = (checksum + checksumContent.charCodeAt(i) * (i+1)) % 1000000;
            }
            exportData.checksum = checksum.toString();

            const jsonData = JSON.stringify(exportData);
            const base64Data = btoa(unescape(encodeURIComponent(jsonData)));

            const blob = new Blob([base64Data], { type: 'application/octet-stream' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', `${studentClass}_${studentName}_答题结果_${new Date().toLocaleDateString().replace(/\//g, '-')}.qres`);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
        }

        // 显示结果
        function showResults() {
            saveCurrentAnswer();
            const score = questions.reduce((total, _, index) => {
                const originalIndex = getOriginalQuestionIndex(index);
                const selectedOption = answers[index];
                const originalOption = selectedOption ? getOriginalOption(originalIndex, selectedOption) : null;
                return total + (originalOption === questions[originalIndex].答案 ? 2 : 0); // 每道题2分
            }, 0);
            
            // 显示总分
            const totalScore = score;
            const resultArea = document.getElementById('resultArea');
            const submitBtn = document.getElementById('submitBtn');
            const restartBtn = document.getElementById('restartBtn');
            const exportBtn = document.getElementById('exportBtn');
            
            // 更新交卷按钮文本
            submitBtn.textContent = `总分：${totalScore}分`;
            submitBtn.disabled = true;
            
            // 显示重新答题和导出结果按钮
            restartBtn.classList.remove('hidden');
            exportBtn.classList.remove('hidden');
            
            // 显示当前题目的结果和解析
            updateResultDisplay();
            
            resultArea.classList.remove('hidden');
            
            // 更新导航按钮颜色（交卷后显示对错）
            renderQuestionNavAfterSubmit();
            
            // 更新状态信息显示
            updateStatusInfo();
        }

        // 重新答题
        function restartQuiz() {
            if (confirm('确定要清空当前答题记录并重新开始吗？')) {
                // 清除答案
                answers = new Array(questions.length).fill(null);
                currentQuestionIndex = 0;
                
                // 清除班级和姓名
                studentClass = '';
                studentName = '';
                studentClassSpan.textContent = '--';
                studentNameSpan.textContent = '--';
                
                // 重新初始化题目顺序
                initQuestionOrder();
                
                // 重置按钮状态
                const submitBtn = document.getElementById('submitBtn');
                const restartBtn = document.getElementById('restartBtn');
                const exportBtn = document.getElementById('exportBtn');
                submitBtn.textContent = '交卷';
                submitBtn.disabled = false;
                restartBtn.classList.add('hidden');
                exportBtn.classList.add('hidden');
                
                // 隐藏结果区域
                const resultArea = document.getElementById('resultArea');
                resultArea.classList.add('hidden');
                
                // 清除本地存储
                clearProgress();
                
                // 显示信息输入弹窗
                infoModal.style.display = 'flex';
                
                // 重置班级选择
                classSelect.value = '';
                nameInput.value = '';
            }
        }

        // 交卷后更新导航按钮颜色
        function renderQuestionNavAfterSubmit() {
            questionNav.innerHTML = '';
            for (let i = 0; i < questions.length; i++) {
                const btn = document.createElement('button');
                btn.textContent = i + 1;
                let btnClass = 'w-9 h-7 rounded-md border text-xs font-bold mb-1 ';
                
                if (i === currentQuestionIndex) {
                    btnClass += 'bg-blue-500 text-white';
                } else if (answers[i] === null) {
                    btnClass += 'bg-gray-100 text-gray-400';
                } else {
                    const originalIndex = getOriginalQuestionIndex(i);
                    const selectedOption = answers[i];
                    const originalOption = getOriginalOption(originalIndex, selectedOption);
                    const isCorrect = originalOption === questions[originalIndex].答案;
                    btnClass += isCorrect ? 'bg-green-200 text-green-700' : 'bg-red-200 text-red-700';
                }
                
                btn.className = btnClass;
                btn.onclick = () => {
                    currentQuestionIndex = i;
                    showCurrentQuestion();
                    renderQuestionNavAfterSubmit();
                };
                questionNav.appendChild(btn);
            }
        }

        // 动态加载 quizdata.js
        function loadQuizDataScript() {
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = 'quizdata.js';
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });
        }

        // 页面加载完成后初始化
        window.addEventListener('load', async function() {
            await loadQuizDataScript();
            if (window.quizData) {
                try {
                    const jsonStr = decodeURIComponent(escape(atob(window.quizData)));
                    questions = JSON.parse(jsonStr);
                } catch (e) {
                    alert('试题数据文件损坏或格式错误！');
                    return;
                }
            } else {
                alert('未找到试题数据文件 quizdata.js！');
                return;
            }
            init();
            
            // 尝试加载保存的进度
            if (loadProgress()) {
                infoModal.style.display = 'none';
            } else {
                infoModal.style.display = 'flex';
            }
        });

        // 页面关闭前保存进度
        window.addEventListener('beforeunload', function(e) {
            if (!answers.every(answer => answer !== null)) {
                saveProgress();
            }
        });
    </script>
</body>
</html> 